<?php

/**
 *      [品牌空间] (C)2001-2010 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: block.inc.php 5697 2011-05-03 07:03:36Z xuhui $
 */

if(!defined('IN_ADMIN')) {
	exit('Acess Denied');
}

require_once(B_ROOT.'./source/adminfunc/tool.func.php');

$blockstr = '';
$block = $blockarr = $checkresults = array();
$_GET['blocktype'] = (!empty($_GET['blocktype']) && in_array($_GET['blocktype'], array('good', 'notice', 'album', 'groupbuy', 'consume'))) ? $_GET['blocktype'] :'';
if(!empty($_POST['deletesubmit'])) {
	if(trim($_POST['operation']) == 'delete') {
		if(!empty($_POST['blockids'])) {
			$blockids = implode(',', $_POST['blockids']);
			DB::query("DELETE FROM ".DB::table('blocks')." WHERE blockid IN ($blockids)");
			cpmsg('message_success', 'admin.php?action=block');
		} else {
			cpmsg('notselect_item', 'admin.php?action=block');
		}
	} else {
		cpmsg('no_operation', 'admin.php?action=block');
	}
}

if(($_GET['op'] == 'edit' || $_GET['op'] == 'add') && !empty($_POST['valuesubmit'])) {

	$blockname = '';
	$blocksqlarr = array();
	$_POST['blocktype'] = !empty($_POST['blocktype']) ? $_POST['blocktype'] : 'sql';
	$_POST['blockname'] = trim($_POST['blockname']);
	!empty($_POST['validity_start']) ? $_POST['validity_start'] = strtotime($_POST['validity_start']): null;
	!empty($_POST['validity_end']) ? $_POST['validity_end'] = strtotime($_POST['validity_end']): null;
	$postarr = array();
	foreach ($_POST as $pkey => $pvalue) {
		$postarr[$pkey] = shtmlspecialchars($pvalue);
	}
	$blocktext = addslashes(serialize($postarr));
	if(empty($_POST['blockname']) || bstrlen($_POST['blockname']) > 10) {
		array_push($checkresults, array('blockname'=>lang('block_blockname_length_error')));
	}
	echo $_POST['blocksql'] = stripcslashes(getblocksql($_POST['blocksql']));
	$blockcodearr[] = $_POST['blocktype'].'/'.rawurlencode($_POST['blocksql']);
	$_POST['blockstart'] = intval($_POST['blockstart']);
	$_POST['blocklimit'] = intval($_POST['blocklimit']);
	if($_POST['blocklimit'] < 1) {
		array_push($checkresults, array('blocklimit'=>lang('block_thread_code_limit')));
	} else {
		$blockcodearr[] = 'limit/'.$_POST['blockstart'].','.$_POST['blocklimit'];
	}
	if(!empty($_POST['tplname']) && !file_exists(B_ROOT.'static/blockstyle/'.$_POST['tplname'].'.html.php')) {
		array_push($checkresults, array('tplnameerror'=>lang('block_tplname_error')));
	}
	if(!empty($checkresults)) {
		cpmsg('add_error', '', 'error', '', true, true, $checkresults);
	}
	$_POST['cachetime'] = intval($_POST['cachetime']);
	if(!empty($_POST['cachetime'])) {
		$blockcodearr[] = 'cachetime/'.$_POST['cachetime'];
	}
	if(!empty($_POST['cachename'])) {
		$blockcodearr[] = 'cachename/'.rawurlencode($_POST['cachename']);
	}
	if(!empty($_POST['tplname'])) {
		$blockcodearr[] = 'tpl/'.rawurlencode($_POST['tplname']);
	}
	if(!empty($_GET['blocktype'])) {
		if($_POST['shopcatid'] != '-1') {
			//
		} else {
			if(!empty($_POST['shopcatid_up'])) {
				foreach($_POST['shopcatid_up'] as $regionid) {
					$_POST['shopcatid'] = $regionid;
				}
			} else {
				$_POST['shopcatid'] = 0;
			}
		}
		
		if($_POST['region'] != '-1') {
			//
		} else {
			if(!empty($_POST['region_up'])) {
				foreach($_POST['region_up'] as $regionid) {
					$_POST['region'] = $regionid;
				}
			} else {
				$_POST['region'] = 0;
			}
		}
		
		if($_POST['catid'] != '-1') {
			//
		} else {
			if(!empty($_POST['catid_up'])) {
				foreach($_POST['catid_up'] as $regionid) {
					$_POST['catid'] = $regionid;
				}
			} else {
				$_POST['catid'] = 0;
			}
		}		
		$blockcodearr[] = 'shopcatid/'.rawurlencode($_POST['shopcatid']);
		$blockcodearr[] = 'region/'.rawurlencode($_POST['region']);
		$blockcodearr[] = 'catid/'.rawurlencode($_POST['catid']);
		if(in_array($_GET['blocktype'], array('consume', 'groupbuy'))) {
			$blockcodearr[] = 'validity_start/'.rawurlencode($_POST['validity_start']);
			$blockcodearr[] = 'validity_end/'.rawurlencode($_POST['validity_end']);
		}
		$blockcodearr[] = 'order/'.rawurlencode($_POST['order']);
		$blockcodearr[] = 'sc/'.rawurlencode($_POST['sc']);
		foreach($_POST['attr_ids'] as $key=>$value) {
			$blockcodearr[] = 'attr_ids_'.$key.'/'.rawurlencode($value);
		}
	}
	$blockcode = '';
	$blockcode .= '<!--{block name="'.$_POST['blocktype'].'" parameter="'.implode('/', $blockcodearr).'"}-->';
	$blockcode .= '<!--'.$_POST['blockname'].'-->';
	$blockcode = addslashes($blockcode);
	$scorename = serialize($scorearr);
	if(!empty($_GET['blocktype'])) {
       // print_r($_POST);
		//echo "REPLACE INTO ".DB::table('blocks')." (blockid, blockname, dateline, blocktext, blockcode, tplname) VALUES ('$_POST[blockid]', '$_POST[blockname]', '$_G[timestamp]', '$blocktext', '$blockcode', '$_POST[tplname]');";
    	//exit();
    }
	DB::query("REPLACE INTO ".DB::table('blocks')." (blockid, blocktype, blockname, dateline, blocktext, blockcode, tplname) VALUES ('$_POST[blockid]', '$_POST[blocktype]', '$_POST[blockname]', '$_G[timestamp]', '$blocktext', '$blockcode', '$_POST[tplname]');");

	cpmsg('message_success', 'admin.php?action=block');

} elseif($_GET['op'] == 'add' || $_GET['op'] == 'edit') {
	if(!empty($_GET['blocktype'])) {
		include_once(B_ROOT.'./source/admininc/admin_blocks_'.$_GET['blocktype'].'_code.inc.php');
	}
	if($_GET['op'] == 'edit') {
		$block = DB::fetch(DB::query("SELECT * FROM ".DB::table('blocks')." WHERE blockid='$_GET[blockid]'"));
		$blockarr = unserialize($block['blocktext']);
		foreach($blockarr['blocktext'] as $key => $value) {
			$blockarr[$key] = $value;
		}
	}
	shownav('global', 'block_'.$_GET['op']);
	showsubmenu('block_add', array(
		array('nav_block', 'block', '0'),
		array('block_add', 'block&op=add', '1')
	));
	showtips('block_'.$_GET['op'].'_tips');
	showformheader('block&op='.$_GET['op'].(!empty($_GET['blocktype']) ? '&blocktype='.$_GET['blocktype'] : ''));
	showtableheader('');
	showsetting('blockname', 'blockname', $blockarr['blockname'], 'text');
	if(!empty($_GET['blocktype'])) {
		showhiddenfields(array('blocktype' => $_GET['blocktype']));

		//echolabel($blockarr['where'], $theblcokvalue);

        $categorylist = getcategory('shop');
        echo '<tr><td class="td27" colspan="2">'.lang('category_shopcatid').'</td></tr><tr><td colspan="2" class="vtop rowform" id="shopcateiddiv">';
        echo InteractionCategoryMenu($categorylist,'shopcatid',$blockarr['shopcatid'],null);
        echo '<span id="span_shopcatid"></span></td></tr>';

        //pkregion(array('alang'=>$mname.'_region', 'name'=>'region', 'options'=>getcategory('region'), 'value'=>$blockarr['region'], 'required'=>$required));
        $categorylist = getcategory('region');
        echo '<tr><td class="td27" colspan="2">'.lang('category_region').'</td></tr><tr><td colspan="2" class="vtop rowform" id="regiondiv">';
        echo InteractionCategoryMenu($categorylist,'region',$blockarr['region'],null);
        echo '<span id="span_region"></span></td></tr>';

       
       
       
        $categorylist = getcategory($_GET['blocktype']);
        echo '<tr><td class="td27" colspan="2">'.lang('category_catid').'</td></tr><tr><td colspan="2" class="vtop rowform" id="'.$showarr['name'].'div">';
        echo InteractionCategoryMenu($categorylist,'catid',$blockarr['catid'],1);
        echo '<span id="span_catid"></span></td></tr>';
		echo '
		<tr class="hover"><td colspan="2"><div id="album_attr"></div></td></tr>
		<script type="text/javascript" charset="'.$_G['charset'].'">
			function getattributes() {
				$("#album_attr").load("batch.attribute.php?ajax=1&blockid='.(!empty($_GET['blockid'])?$_GET['blockid']:'0').'&typeid="+$("select[name=catid]").val());
			}
		</script>';
		if(in_array($_GET['blocktype'], array('consume', 'groupbuy'))) {
			$blockarr['validity_start'] = !empty($blockarr['validity_start'])?date("Y-m-d", $blockarr['validity_start']):'';
			$blockarr['validity_end'] = !empty($blockarr['validity_end'])?date("Y-m-d", $blockarr['validity_end']):'';
			showsetting('validity_start','validity_start', $blockarr['validity_start'], 'calendar');
			showsetting('validity_end', 'validity_end', $blockarr['validity_end'], 'calendar');
			echo '<script type="text/javascript" charset="'.$_G['charset'].'">loadcalendar();</script>';

		}
		$search_items[] = 'order'.
				'::<select id="order" name="order">'.
				'<option value="itemid"'.($blockarr['order'] == 'itemid'?' selected':'').'>'.lang($mname.'_dateline').'</option>'.
				'<option value="lastpost"'.($blockarr['order'] == 'lastpost'?' selected':'').'>'.lang('lastpost').'</option>'.
				'<option value="viewnum"'.($blockarr['order'] == 'viewnum'?' selected':'').'>'.lang('viewnum').'</option>'.
				'<option value="replynum"'.($blockarr['order'] == 'replynum'?' selected':'').'>'.lang('replynum').'</option>'.
				'</select>';
		$search_items[] = 'sc'.
				'::<select id="sc" name="sc">'.
				'<option value="ASC"'.($blockarr['sc'] == 'ASC'?' selected':'').'>'.lang('ASC').'</option>'.
				'<option'.(empty($blockarr['sc'])?' selected':'').' value="DESC"'.($blockarr['sc'] == 'DESC'?' selected':'').'>'.lang('DESC').'</option>'.
				'</select>';
		foreach($search_items as $k=>$v){
			$tmp = explode('::',$v);
			showsetting($tmp[0], '', '',$tmp[1]);
		}

	} else {
		showsetting('blocksql', 'blocksql', stripcslashes($blockarr['blocksql']), 'textarea');
	}
	showsetting('blockstart', 'blockstart', $blockarr['blockstart'], 'text');
	showsetting('blocklimit', 'blocklimit', $blockarr['blocklimit'], 'text');
	showsetting('cachetime', 'cachetime', $blockarr['cachetime'], 'text');
	showsetting('cachename', 'cachename', $blockarr['cachename'], 'text');
	if($_GET['op'] == 'add' && !empty($_GET['blocktype'])) {
		$blockarr['tplname'] = 'default_'.$_GET['blocktype'].'_block';
	}
	showsetting('tplname', 'tplname', $blockarr['tplname'], 'text');
	showhiddenfields(array('blockid' => $_GET['blockid']));
	showsubmit('valuesubmit');
	showtablefooter();
	showformfooter();
	bind_ajax_form();

} else {

	shownav('global', 'block_list');
	showsubmenu('nav_block', array(
		array('nav_block', 'block', '1'),
		array('block_add', 'block&op=add', '0')
	));
	showtips('block_list_tips');
	echo '<div class="wel">
					<div class="welheader"><h1>'.lang("block_menu_blcoktype").'</h1></div>
					<div class="welc"><a href="admin.php?action=block&op=add&blocktype=good">'.lang("block_menu_addblcoktype_good").'</a> || <a href="admin.php?action=block&op=add&blocktype=notice">'.lang("block_menu_addblcoktype_notice").'</a> || <a href="admin.php?action=block&op=add&blocktype=consume">'.lang("block_menu_addblcoktype_consume").'</a> || <a href="admin.php?action=block&op=add&blocktype=album">'.lang("block_menu_addblcoktype_album").'</a> || <a href="admin.php?action=block&op=add&blocktype=groupbuy">'.lang("block_menu_addblcoktype_groupbuy").'</a></div>
				</div>';
	showformheader('block');
	showtableheader('');
	showsubtitle(array('<input type="checkbox" onclick="checkall(this.form, \'blockids\')" name="chkall" >', 'blockid', 'blockname', 'block_dateline', 'blcokcode', 'block_operation'));

	$query = DB::query('SELECT * FROM '.DB::table('blocks').' ORDER BY blockid ASC');
	while($block = DB::fetch($query)) {
		foreach(unserialize($block['scorename']) as $scorename) {
			$block['scorenamestr'] .= '['.$scorename.']';
		}
		$blockarr[] = $block;
	}
	foreach($blockarr as $value) {
		$textarea = '';
		preg_match("/parameter\=\"(.*?)\"/is", $value['blockcode'], $matches);
		if(!empty($matches[1]) && strpos($matches[1], 'tpl/data') === false) {
			$value['blocktype'] = empty($value['blocktype'])? 'sql':$value['blocktype'];
			$value['jscode'] = '<script charset="utf-8" language="JavaScript" src="'.B_URL.'batch.javascript.php?param='.rawurlencode(passport_encrypt('blocktype/'.$value['blocktype'].'/'.$matches[1], $_G['setting']['sitekey'])).'"></script>';
		}
		$textarea = !empty($value['tplname'])?lang('showblockcode').'<br /><textarea cols="55" rows="3">'.$value['blockcode'].'</textarea><br />'.lang('showjsblockcode').'<br /><textarea cols="55" rows="3">'.$value['jscode'].'</textarea>':'<textarea cols="55" rows="3">'.$value['blockcode'].'</textarea>';
		showtablerow('', array(), array("<input class='checkbox' type='checkbox' name='blockids[]' value='$value[blockid]' />", $value['blockid'], $value['blockname'], date('Y-m-d', $value['dateline']), $textarea, '<a href="admin.php?action=block&op=edit&blockid='.$value['blockid'].(!empty($value['blocktype'])?'&blocktype='.$value['blocktype']:'').'">'.lang('blockedit').'</a>'));
	}
	showcommentmod(false);
	showtablefooter();
	showformfooter();
	bind_ajax_form();
}
//加密函数
function passport_encrypt($txt, $key) {
	srand((double)microtime() * 1000000);
	$encrypt_key = md5(rand(0, 32000));
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen($txt); $i++) {
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
	}
	return base64_encode(passport_key($tmp, $key));
}

//加密函数
function passport_key($txt, $encrypt_key) {
	$encrypt_key = md5($encrypt_key);
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen($txt); $i++) {
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
	}
	return $tmp;
}
?>